package org.projectback.controller;

import jakarta.annotation.Resource;
import org.projectback.entity.AccountEntity.CustomUser;
import org.projectback.entity.FileEntity.DTO.FileDTO;
import org.projectback.service.ModifyService.ModifyService;
import org.projectback.service.SarchService.SearchService;
import org.projectback.utils.ResultMessage;
import org.projectback.utils.Utils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author K·K
 * @version 1.0
 * @Date 2025/10/9
 */
@RestController
public class ModifyController {
    @Resource
    private ModifyService modifyService;
    @Resource
    private SearchService searchService;
    @Resource
    private Utils utils;

    /**
     * 上传文件接口
     *
     * @return 操作是否成功
     */
    @PostMapping("/api/user/uploadFile")
    public ResultMessage<Object> createFile(@RequestParam("file") MultipartFile file) {
        String username = getCurrentUsername();
        long userId = getUserId();
        boolean upload = modifyService.upload(file,userId,username);
        return upload ? ResultMessage.success(200, username) : ResultMessage.failure(402, username);
    }

    /**
     * 删除某个文件
     *
     * @return 操作是否成功
     */
    @GetMapping("/api/user/deleteFile")
    public ResultMessage<String> deleteFile(@RequestParam("fileName") String fileName) {
        return modifyService.delete(fileName) ? ResultMessage.success(200, fileName) : ResultMessage.failure(402, fileName);
    }

    /**
     * 通过文件名来查找对应的文件
     *
     * @param fileName 文件名
     */
    @GetMapping("/api/user/getFile")
    public ResultMessage<String> getFile(@RequestParam("fileName") String fileName) {
        long userId = getUserId();
        if (userId==-1) {
            return ResultMessage.unauthorized();
        }
        FileDTO fileDTO = searchService.getFileDTO(userId, fileName);
        return ResultMessage.success(200, utils.objectToJsonString(fileDTO));
    }

    private String getCurrentUsername() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated() || !(auth.getPrincipal() instanceof CustomUser user)) {
            return "";
        }
        return user.getUsername();
    }
    private long getUserId() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated() || !(auth.getPrincipal() instanceof CustomUser user)) {
            return -1;
        }
        return user.getId();
    }
}
